<template>
    <div id="login">
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol" class="loginForm">
            <a-form-item label="用户名" v-bind="validateInfos.username">
                <a-input
                        v-model:value="modelRef.username"
                        @blur="validate('username', { trigger: 'blur' }).catch(() => {})"
                        placeholder="用户名"
                />
            </a-form-item>
            <a-form-item label="密码" v-bind="validateInfos.password">
                <a-input
                        type="password"
                        v-model:value="modelRef.password"
                        @blur="validate('password', { trigger: 'blur' }).catch(() => {})"
                        placeholder="密码"
                />
            </a-form-item>
            <a-form-item label=" " :colon="false">
                <a-button type="primary" @click.prevent="onSubmit" size="large" block>提交</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script lang="ts">
    import {
        api_getLoginInfo
    } from "@api";
    import saveData from "@store/storage";

	import { useRouter } from "vue-router";
    import {defineComponent, reactive, toRaw} from "vue";
	import { useForm } from "@ant-design-vue/use";
	export default defineComponent({
        setup(){
			const modelRef = reactive({
				username: '',
				password: '',
			});
			const rulesRef = reactive({
				username: [
					{
						required: true,
						message: '请输入用户名',
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
					},
				],
			});

			let { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);

			const onSubmit = () => {
				validate()
					.then(() => {
						// toRaw - 响应式对象转普通对象
                        api_getLoginInfo(toRaw(modelRef)).then(res=>{
                            if(res.code == 200){
                                saveData.storage.setItem('loginInfo',res.data)
                                gotoCenter('/center')
                            }
                        })
					})
					.catch(err => {
						console.log('error', err);
					});
			};

			const router = useRouter();
			function gotoCenter(path: string){
				router.replace(path);
			}

			return {
				labelCol: {
					span: 4,
				},
				wrapperCol: {
					span: 14,
				},
				validate,
				validateInfos,
				resetFields,
				modelRef,
				onSubmit,
			};
		},
	});
</script>

<style lang="scss">
    #login{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        .loginForm{
            width: 500px;
        }
    }
</style>
